import React, { useState, useEffect } from "react";
import { Form, Drawer, Button, message } from "antd";
import FormBuilder from 'antd-form-builder';
import { addUser, modifyUser } from "@/api/user";
import AvatarUploader from '@/components/Upload/Uploadavatar'



const EditForm = props => {
	const [form] = Form.useForm();
	const { onCancel, } = props;
	const [visible, setVisisble] = useState(props.visible)
	const [title, setTitle] = useState(props.title)
	const [editModalLoading, setEditModalLoading] = useState(false)
	const [editMode, setEditMode] = useState(false)
	const [avatar, setavatar] = useState('') // 上传组件默认显示

	useEffect(() => {
		setTitle(props.title)
	}, [props.title])

	useEffect(() => {
		setVisisble(props.visible)
	}, [props.visible])


	useEffect(() => {
		setEditMode(props.editMode)
		props.currentRowData.avatar && setavatar(props.currentRowData.avatar)
		// 编辑回填内容 新增清空内容 
		const initValue = props.editMode ? props.currentRowData : { status: 0 };
		form.setFieldsValue(initValue);
	}, [props.currentRowData, props.editMode])


	// 取消，关闭抽屉 重置表单
	const handleCancel = () => {
		form.resetFields();
		setavatar('')
		onCancel && onCancel();
	};

	// 验证通过 开始进行 新增/编辑 请求
	const handleSubmit = () => {
		let fieldsValue = form.getFieldsValue();
		setEditModalLoading(true)
		const handler = editMode ? modifyUser : addUser;
		// 服务端要求的参数格式
		const params = editMode ? {
			id: props.currentRowData.userId,
			nickName: fieldsValue.nickName,
			avatar: fieldsValue.avatar,
			realName: fieldsValue.realName,
			// status: fieldsValue.status
		} : {
				user: {
					nickName: fieldsValue.nickName,
					avatar: fieldsValue.avatar,
					realName: fieldsValue.realName,
					// status: fieldsValue.status
				},
				auth: {
					identityType: 0, // 固定填0（0为管理平台用户）
					identifier: fieldsValue.identifier, // 系统内用户唯一标识（用户名
					credential: fieldsValue.credential //用户登陆密码
				}
			}
		handler(params).then(() => {
			message.success(`${editMode ? '编辑' : '新增'} 用户成功!`)
			handleCancel();
			props.onOk && props.onOk();
		}).catch(e => {
			message.error("错误，请重试!")
		}).finally(() => {
			setEditModalLoading(false)
		})
	};

	const formItemLayout = {
		labelCol: {
			sm: { span: 4 },
		},
		wrapperCol: {
			sm: { span: 16 },
		},
	};
	// 上传组件 成功回调处理
	const handleUploadOk = avatar => {
		form.setFieldsValue({
			avatar
		})
	}



	const meta = {
		fields: [
			{
				key: 'realName',
				label: '真实姓名',
			},
			{
				key: 'nickName',
				label: '昵称',
			},
			{ key: 'avatar', label: 'Avatar', widget: AvatarUploader, widgetProps: { onUploadOk: handleUploadOk, avatar } },
			{
				key: 'identifier',
				label: '用户名',
				rules: [{ required: true, message: "请输入用户名称" }]
			},

			// {
			// 	key: 'status',
			// 	label: '用户状态',
			// 	widget: 'select',
			// 	options: [
			// 		{
			// 			label: '可用',
			// 			value: 0
			// 		},
			// 		{
			// 			label: '禁用',
			// 			value: 1
			// 		}
			// 	]
			// }
		],
	}

	if (!editMode) {
		meta.fields.push({
			key: 'credential',
			label: '密码',
			rules: [{ required: true, message: "请输入用户密码" }]
		});
	}

	return (
		<Drawer
			title={title}
			visible={visible}
			width={500}
			maskClosable={false}
			placement="right"
			getContainer={false}
			onClose={handleCancel}
		>
			<Form {...formItemLayout} form={form} onFinish={handleSubmit} >
				<FormBuilder meta={meta} form={form} />
				<Form.Item>
					<Button type="primary" htmlType="submit" loading={editModalLoading} className="drawer-submit-button"> 提交 </Button>
				</Form.Item>
			</Form>
		</Drawer>
	);
}

export default EditForm;
